<?php
/*
 * @Descripttion:
 * @version:
 * @Author: ewgof
 * @Date: 2020-08-11 15:04:25
 * @LastEditors: ewgof
 * @LastEditTime: 2020-10-09 21:17:31
 */
namespace cw;

use cw\File;
use cw\interfaces\ConfigInterface;


class Config extends Base implements ConfigInterface
{
    protected $config = [];

    public function __construct()
    {
        global $config;

        $this->config = &$config;

        if (!$this->config) {
            $files = (new File())->scandir(__CONFIG__);
            // unset($files[array_keys($files, '.')], $files[array_keys($files, '..')])
            // var_dump($files);
            foreach ($files as $fk => $fv) {
                $key = substr($fv, 0, strpos($fv, '.'));
                // var_dump($key);
                if ($fv == '.' || $fv == '..') {
                    continue;
                }
                $this->config[$key] = require_once __CONFIG__ . $fv;
            }
        }
    }


    public function get(String $name = '')
    {
        if (empty($name)) {
            return $this->config;
        }
        $key_arr = explode('.', $name);
        $config_once = $this->config;
        foreach ($key_arr as $nk => $nv) {
            $p = $config_once[$nv];
            $config_once = $p;
        }
        return $p;
    }


    /**
     * @name: set
     * @msg: 动态设置配置参数的值,最多可以设置 5 个层级
     * @param string $name 参数名称
     * @param string $val 参数值
     * @return {type} 
     */
    public function set(String $name, String $val)
    {
        if (empty($name) || empty($val)) {
            return false;
        }
        $key_arr = explode('.', $name);
        $count = count($key_arr);
        if ($count > 5 || $count < 1) {
            return false;
        }
        switch ($count) {
            case 1:
                $this->config[$key_arr[0]] = $val;
                break;
            case 2:
                $this->config[$key_arr[0]][$key_arr[1]] = $val;
                break;
            case 3:
                $this->config[$key_arr[0]][$key_arr[1]][$key_arr[2]] = $val;
                break;
            case 4:
                $this->config[$key_arr[0]][$key_arr[1]][$key_arr[2]][$key_arr[3]] = $val;
                break;
            case 5:
                $this->config[$key_arr[0]][$key_arr[1]][$key_arr[2]][$key_arr[3]][$key_arr[4]] = $val;
                break;
        }
        return true;
    }
}
